package com.jstyle.jclife.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.SleepMonthDetailAdapter;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.SleepDataDaoManager;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.SleepData;
import com.jstyle.jclife.model.SleepShowData;
import com.jstyle.jclife.utils.ChartDataUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SleepMonthFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SleepMonthFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.bt_sleep_month_pre)
    ImageView btSleepMonthPre;
    @BindView(R.id.bt_sleep_month_date)
    Button btSleepMonthDate;
    @BindView(R.id.bt_sleep_month_next)
    ImageView btSleepMonthNext;
    @BindView(R.id.CalendarView_sleep_Month)
    CalendarView CalendarViewSleepMonth;
    Unbinder unbinder;
    //    @BindView(R.id.recyclerView)
//    RecyclerView recyclerView;

    @BindView(R.id.ColumnChartView_sleepMonth)
    ColumnChartView ColumnChartViewSleepMonth;
    @BindView(R.id.LineChartView_sleepHeart_month)
    LineChartView LineChartViewSleepHeartMonth;
    @BindView(R.id.RecyclerView_sleepMonth_detail)
    RecyclerView RecyclerViewSleepMonthDetail;
    @BindView(R.id.CalendarLayout)
    com.haibin.calendarview.CalendarLayout CalendarLayout;
    @BindView(R.id.bt_month_avgHr)
    Button btMonthAvgHr;

    private String thisMonth;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private String[] monthDates;
    private SleepMonthDetailAdapter sleepMonthDetailAdapter;
    private HashMap<String, SleepShowData> markHashMap = new HashMap<>();
    private static final String TAG = "SleepMonthFragment";
    private boolean isBusy;
    private HashMap<String, Float> heartRateMap = new HashMap<>();

    public SleepMonthFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SleepMonthFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SleepMonthFragment newInstance(String param1, String param2) {
        SleepMonthFragment fragment = new SleepMonthFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.i(TAG, "onCreateView: ");
        View view = inflater.inflate(R.layout.fragment_sleep_month, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        initChartView();
        return view;
    }

    private void initChartView() {
        monthDates = DateUtil.getThisMonth();
        findMonthData();
    }

    private void init() {
        List<String> list = new ArrayList<>();
        list.add(getString(R.string.avg_awake));
        list.add(getString(R.string.Avg_deep));
        list.add(getString(R.string.avg_light));
        sleepMonthDetailAdapter = new SleepMonthDetailAdapter(list);
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getActivity());
        RecyclerViewSleepMonthDetail.setLayoutManager(layoutManager);
        RecyclerViewSleepMonthDetail.setAdapter(sleepMonthDetailAdapter);
        thisMonth = DateUtil.getMonthString("", DateUtil.this_month);


    }

    private void findMonthData() {
        String monthDate=DateUtil.getShowMonthDate(getActivity(), monthDates[0]);
        btSleepMonthDate.setText(monthDate);
        btSleepMonthNext.setEnabled(DateUtil.monthEnable(getActivity(),monthDate));
        markHashMap.clear();
        mergeSleepData();

    }

    private void mergeSleepData() {
        List<Observable<Integer>> observables = new ArrayList<>();
        for (String date : monthDates) {
            observables.add(getDayObservable(date));
        }
        showLoadingDialog();
        Observable.merge(observables).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer value) {
                Log.i(TAG, "onNext: " + value);
            }

            @Override
            public void onError(Throwable e) {
                disMissLoadingDialog();
                isBusy = false;
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                disMissLoadingDialog();
                setRecycleViewData();
                setChartViewData();
                setHeartChartViewData();
                setCalenderViewData();
                isBusy = false;
            }
        });
    }

    private void setCalenderViewData() {
        Map<String, Calendar> map = new HashMap<>();
        for (Map.Entry<String, SleepShowData> entry : markHashMap.entrySet()) {
            int level = entry.getValue().getSleepLevel();
            int color = getSleepLevelColor(level);
            String date = "20" + entry.getKey();
            String[] dateArray = date.split("\\.");
            Calendar calendar = getSchemeCalendar(Integer.valueOf(dateArray[0]), Integer.valueOf(dateArray[1]), Integer.valueOf(dateArray[2]), color, "");
            map.put(calendar.toString(), calendar);
        }
        CalendarViewSleepMonth.setSchemeDate(map);
    }

    private int getSleepLevelColor(int level) {
        int color = 0;
        if (level == 4) {
            color = R.color.week_sleep_deep;
        } else if (level == 3) {
            color = R.color.week_sleep_light;
        } else if (level == 2) {
            color = R.color.week_sleep_awake;
        } else if (level == 1) {
            color = R.color.week_sleep_rem;
        }
        return getActivity().getResources().getColor(color);
    }

    private void setChartViewData() {
        ChartDataUtil.initDataChartView(ColumnChartViewSleepMonth, -1, maxSleepTime < 8 ? 8.5f : maxSleepTime * 1.2f, monthDates.length, 0);
        ColumnChartViewSleepMonth.setColumnChartData(ChartDataUtil.getMonthColumnChart(getActivity(), monthDates, markHashMap));

    }

    float maxSleepTime = 0;

    private void setRecycleViewData() {
        maxSleepTime = 0;
        float awakeTime = 0;
        float deepTime = 0;
        float lightTime = 0;
        float days = markHashMap.size();
        for (Map.Entry<String, SleepShowData> entry : markHashMap.entrySet()) {
            SleepShowData sleepShowData = entry.getValue();
            float awake = sleepShowData.getAwakeTime();
            float deep = sleepShowData.getDeepTime();
            float light = sleepShowData.getLightTime();
            maxSleepTime = Math.max(maxSleepTime, awake + deep + light);
            awakeTime += awake * 60f;
            deepTime += deep * 60f;
            lightTime += light * 60f;
        }
        float avgAwake = days == 0 ? 0 : awakeTime / days;
        float avgDeep = days == 0 ? 0 : deepTime / days;
        float avgLight = days == 0 ? 0 : lightTime / days;
        List<String> list = new ArrayList<>();
        list.add(DateUtil.getPointSleepTime(getActivity(), avgAwake));
        list.add(DateUtil.getPointSleepTime(getActivity(), avgDeep));
        list.add(DateUtil.getPointSleepTime(getActivity(), avgLight));
        sleepMonthDetailAdapter.setStepData(list);
        // tvSleepweekAvgtime.setText(DateUtil.getPointSleepTime(getActivity(), avgTotal));
        //  tvSleepweekDeeptime.setText(DateUtil.getPointSleepTime(getActivity(), avgDeep));
        //  tvSleepweekLighttime.setText(DateUtil.getPointSleepTime(getActivity(), avgLight));
    }

    private Observable<Integer> getDayObservable(final String date) {
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                String startDate = DateUtil.getTomorrowDateString(date);
                Log.i(TAG, "subscribe: sleep "+date);
                List<SleepData> sleepDataList = SleepDataDaoManager.queryData(date, startDate);
                List<HeartData> heartDataList = HeartDataDaoManager.queryData(date, startDate);
                int[] sleepData = getSleepData(sleepDataList, date);
                float[]showData=getShowSleepData(sleepData);
                getHeartRate(heartDataList,sleepData,date);
                int[] sleepLevel = new int[3];
                for (float value : showData) {
                    if (value != 0) sleepLevel[ResolveData.getSleepLevel((int) value)]++;
                }
              //waitS();
                float deep = sleepLevel[0] * 5;
                float light = sleepLevel[1] * 5;
                float awake = sleepLevel[2] * 5;
                float total = deep + light + awake;
                int id = ResolveData.getSleepQualityLevel(deep, light);
                SleepShowData sleepShowData = new SleepShowData();
                sleepShowData.setAwakeTime(awake / 60f);
                sleepShowData.setDate(date);
                sleepShowData.setDeepTime(deep / 60f);
                sleepShowData.setLightTime(light / 60f);
                sleepShowData.setTotalTime(total / 60f);
                sleepShowData.setSleepLevel(id);
                Log.i(TAG, "subscribe: "+id);
                if (id != 0) markHashMap.put(date, sleepShowData);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io());

    }
    private void getHeartRate(List<HeartData> heartDataList,int[] sleepData,String date) {
        List<Integer>listSleep=new ArrayList<>();
        for(int i=0;i<sleepData.length;i++){
            int value=  sleepData[i];
            if(value!=-1){
                for(int j=0;j<5;j++){
                    listSleep.add(i*5+j);
                }
            }
        }
        float totalHR = 0;
        float count = 0;
        int[] heartDataArray = new int[1440];//1分钟一个点。一天1440
        for (HeartData data : heartDataList) {
            String time = data.getTime();
            int value = data.getHeart();
            int startCount = DateUtil.get1MIndex(time, date + " 12:00:00");
            if (startCount >= 1440) break;
            if(listSleep.contains(startCount)){
                if(value!=0){
                    count++;
                    totalHR+=value;
                }
            }

        }
        float avgHeart = count == 0 ? 0 : totalHR / count;
        heartRateMap.put(date, avgHeart);
    }

    private int[] getSleepData(List<SleepData> sleepDataList, String startDate) {
        int[] fiveSleepData = new int[288];//288*5分钟
        for(int i=0;i<fiveSleepData.length;i++){
            fiveSleepData[i]=-1;//睡眠数据0为有效数据
        }
        for (SleepData sleepData : sleepDataList) {
            String time = sleepData.getTime();
            String data = sleepData.getDateString();
            int startCount = DateUtil.get5MIndex(time, startDate + " 12:00:00");
            if (startCount >= 288) break;
            fiveSleepData[startCount] = Integer.valueOf(data);
        }
        return fiveSleepData;
    }


    private float[] getShowSleepData(int[] fiveSleepData) {
        float[] showData = new float[fiveSleepData.length];
        int length = fiveSleepData.length;
        out:
        for (int i = 0; i < length; i++) {//取5分钟的平均值
            float total = 0;
            float count = 0;
            for (int j = 0; j < 5; j++) {
                int position = i + j;
                if (position < length) {
                    int data = fiveSleepData[position];
                    if (data != -1) {
                        total += data;
                        count++;
                    }
                } else {
                    showData[i] = count == 0 ? 0 : total / count;
                    continue out;
                }

            }
            showData[i] = count == 0 ? 0 : total / count;
        }
        return showData;
    }


    private void mergeHeartData() {
        List<Observable<Integer>> observables = new ArrayList<>();
        for (String date : monthDates) {
            observables.add(getHeartObservable(date));
        }
        Observable.merge(observables).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer value) {
                Log.i(TAG, "onNext: " + value);
            }

            @Override
            public void onError(Throwable e) {

                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.i(TAG, "onComplete: ");
                setHeartChartViewData();
            }
        });
    }

    private void setHeartChartViewData() {
        ChartDataUtil.initDataChartView(LineChartViewSleepHeartMonth, -1, 110, monthDates.length, 0);
        LineChartViewSleepHeartMonth.setLineChartData(ChartDataUtil.getSleepMonthHeartChart(getActivity(), monthDates, heartRateMap));
        float total = 0;
        float size = 0;
        for (Map.Entry<String, Float> entry : heartRateMap.entrySet()) {
            total += entry.getValue();
            if (entry.getValue() != 0) size++;
        }
        int avg = size == 0 ? 0 : (int) (total / size);
        btMonthAvgHr.setText("Avg "+avg+"bpm");
    }

    private Observable<Integer> getHeartObservable(final String date) {
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                String startDate = DateUtil.getTomorrowDateString(date);
                List<HeartData> heartDataList = HeartDataDaoManager.queryData(date, startDate);
                float total = 0;
                float count = 0;
                for (HeartData data : heartDataList) {
                    if (data.getHeart() != 0) {
                        total += data.getHeart();
                        count++;
                    }
                }
                float avgHeart = count == 0 ? 0 : total / count;
                heartRateMap.put(date, avgHeart);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io());
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.bt_sleep_month_pre, R.id.bt_sleep_month_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_sleep_month_next:
                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.next_month);
                monthDates = DateUtil.getNextMonth(monthDates[0]);
                if (!CalendarLayout.isExpand()) CalendarLayout.expand();
                CalendarViewSleepMonth.scrollToNext(true);
                findMonthData();
                break;
            case R.id.bt_sleep_month_pre:
                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.last_month);
                monthDates = DateUtil.getLastMonth(monthDates[0]);
                if (!CalendarLayout.isExpand()) CalendarLayout.expand();
                CalendarViewSleepMonth.scrollToPre(true);
                findMonthData();
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    @Override
    public void shoot() {
        super.shoot();
       ScreenUtils.shareFile(getActivity(), CalendarLayout);
    }
}
